package com.ruoyi.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.common.util.CopyEntity;
import com.common.util.ListConvertMap;
import com.common.util.MergeDataSource;
import com.param.impl.DiscountParam;
import com.param.impl.UpdateByDuplicateCheckCoupon;
import com.param.impl.UpdateByRecommend;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.user.domain.MgUser;
import com.ruoyi.user.domain.UserByDeposit;
import com.ruoyi.user.service.IMgUserService;

import io.swagger.annotations.ApiOperation;

import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.config.manager.domain.MgIdentity;
import com.ruoyi.config.manager.service.IMgIdentityService;
import com.ruoyi.management.domain.CommissionManagement;
import com.ruoyi.management.service.ICommissionManagementService;
import com.ruoyi.team.domain.vo.MgTeam;
import com.ruoyi.team.service.ITeamInformationService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * userManagerController
 * 
 * @author ruoyi
 * @date 2023-12-19
 */
@RestController
@RequestMapping("/userManager/user")
public class MgUserController extends BaseController
{
    private IMgUserService mgUserService;
    
    private IMgIdentityService identityService;
    
    ITeamInformationService teamInformationService;
    
    ICommissionManagementService commissionManagementService;
    
    @Resource
    public void setCommissionManagementService(ICommissionManagementService commissionManagementService) {
		this.commissionManagementService = commissionManagementService;
	}


	@Resource
    public void setTeamInformationService(ITeamInformationService teamInformationService) {
		this.teamInformationService = teamInformationService;
	}
    

	public MgUserController(IMgUserService mgUserService) {
    	this.mgUserService = mgUserService;
    }

    /**
     * 查询userManager列表
     */
    @PreAuthorize("@ss.hasPermi('userManager:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(MgUser mgUser)
    {
        startPage();
        List<MgUser> list = mgUserService.selectMgUserList(mgUser);
        return getDataTable(list);
    }
    
    /**
     * 预付款导出
     * @param response
     * @param mgUser
     */
    
    @PreAuthorize("@ss.hasPermi('userManager:user:export')")
    @Log(title = "userManager", businessType = BusinessType.EXPORT)
    @PostMapping("/exportByDepoist")
    public void exportByDepoist(HttpServletResponse response, MgUser mgUser)
    {
        List<MgUser> list = mgUserService.selectMgUserList(mgUser);
        
        List<UserByDeposit> deposits = new ArrayList<UserByDeposit>();
        
        for (MgUser user : list) {
        	deposits.add(CopyEntity.copyEntity(user, UserByDeposit.class));
        }
        
        ExcelUtil<UserByDeposit> util = new ExcelUtil<UserByDeposit>(UserByDeposit.class);
        util.exportExcel(response, deposits, "预付款数据", "预付款数据");
    }

    
    
    /**
     * 导出userManager列表
     */
    @PreAuthorize("@ss.hasPermi('userManager:user:export')")
    @Log(title = "userManager", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MgUser mgUser)
    {
        List<MgUser> list = mgUserService.selectMgUserList(mgUser);
        
        if (0 == list.size()) return;
        
        List<MgIdentity> selectMgIdentityList = identityService.selectMgIdentityList(new MgIdentity());
        
        Map<Integer, MgIdentity> listToMap = ListConvertMap.listToMap(selectMgIdentityList, MgIdentity::getId);
        
        MergeDataSource<MgUser> mergeDataSource = new MergeDataSource<MgUser>(list);
        
        mergeDataSource.mergeRelease(MgUser::getIdentity, listToMap, (u, i) -> {
        	u.setIdentityName(i.getIdentityName());
            u.setMembershipName(u.getTeamId()==0?"普通会员" : "签约会员");
        	return u;
        });
        
        List<MgTeam> teamList = teamInformationService.getTeamList(list.stream().mapToLong(e->e.getTeamId()).distinct().toArray());
        
        if (0 != teamList.size()) {
        	
            Map<Integer, MgTeam> teamToMap = ListConvertMap.listToMap(teamList, MgTeam::getId);

            mergeDataSource.mergeRelease(e->e.getTeamId().intValue(), teamToMap, (u, i) -> {
            	u.setTeamName(i.getGroupName());
            	return u;
            });
        };
        
        
        ExcelUtil<MgUser> util = new ExcelUtil<MgUser>(MgUser.class);
        util.exportExcel(response, list, "userManager数据");
    }

    /**
     * 获取userManager详细信息
     */
    @PreAuthorize("@ss.hasPermi('userManager:user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(mgUserService.selectMgUserById(id));
    }

    /**
     * 设置查重券
     */
    @PreAuthorize("@ss.hasPermi('userManager:user:duplicateCheckCoupon')")
    @Log(title = "userManager", businessType = BusinessType.UPDATE)
    @PostMapping("duplicateCheckCoupon")
    public AjaxResult duplicateCheckCoupon(@RequestBody @Validated UpdateByDuplicateCheckCoupon mgUser)
    {
        return toAjax(mgUserService.updateDuplicateCheckCoupon(mgUser));
    }
    
    /**
     * 设置折扣
     */
    @PreAuthorize("@ss.hasPermi('userManager:user:duplicateCheckCoupon')")
    @Log(title = "userManager", businessType = BusinessType.UPDATE)
    @PostMapping("configDiscount")
    @ApiOperation(value = "设置折扣", tags = {"设置折扣"})
    public AjaxResult configDiscount(@RequestBody @Validated DiscountParam mgUser)
    {
        return toAjax(mgUserService.updateDiscount(mgUser));
    }

    
    /**
     * 设置推荐人
     */
    @PreAuthorize("@ss.hasPermi('userManager:user:recommend')")
    @Log(title = "userManager", businessType = BusinessType.UPDATE)
    @PostMapping("updateRecommend")
    @Transactional
    public AjaxResult updateRecommend(@RequestBody @Validated UpdateByRecommend updateByRecommend)
    {
    	Integer recommendedUserId = updateByRecommend.getRecommendedUserId();
		MgUser selectById = this.mgUserService.selectById(recommendedUserId);
    	
    	if (null == selectById) {
    		
            return AjaxResult.error("推荐人不存在");
    	}
    	
        int updateRecommend = mgUserService.updateRecommend(updateByRecommend);
        
        this.commissionManagementService.parseCommissionManagement(recommendedUserId, selectById.getRealname());
        
		return toAjax(updateRecommend);
    }
    
    /**
     * 修改userManager
     */
    @PreAuthorize("@ss.hasPermi('userManager:user:edit')")
    @Log(title = "userManager", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MgUser mgUser)
    {
        return toAjax(mgUserService.updateMgUser(mgUser));
    }

    /**
     * 删除userManager
     */
    @PreAuthorize("@ss.hasPermi('userManager:user:remove')")
    @Log(title = "userManager", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(mgUserService.deleteMgUserByIds(ids));
    }

    @Resource
	public void setIdentityService(IMgIdentityService identityService) {
		this.identityService = identityService;
	}
}
